package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"rpc_demo/steam_grpc_test/proto"
	"sync"
)

type C struct {
}

func main() {
	//host := "192.168.3.17"
	//port := ":50051"
	//client, err := grpc.NewClient(fmt.Sprintf("%s:%s", host, port), grpc.WithTransportCredentials(insecure.NewCredentials()))
	interceptor := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {

		pairs := metadata.Pairs(
			"appid", "234",
			"name", "king",
		)
		outgoingContext := metadata.NewOutgoingContext(ctx, pairs)
		err := invoker(outgoingContext, method, req, reply, cc, opts...)
		if err != nil {
			return err
		}
		return err
	}

	var opts []grpc.DialOption
	//opt := append(opts,grpc.WithTransportCredentials())
	opt := append(opts, grpc.WithUnaryInterceptor(interceptor))
	client, err := grpc.NewClient("localhost:50051", opt...)

	if err != nil {
		panic(err)
	}
	//defer client.Close()
	greeterClient := proto.NewGreeterClient(client)
	//stream, err := greeterClient.GetStream(context.Background(), &proto.StreamReqData{
	//	Data:     "dasfdasf",
	//	Birthday: timestamppb.New(time.Now()),
	//})
	//stream, err := greeterClient.PutStream(context.Background())

	md := metadata.New(map[string]string{"k1": "v1", "k2": "v2"})
	ct := metadata.NewOutgoingContext(context.Background(), md)
	stream, err := greeterClient.AllStream(ct)
	if err != nil {
		return
	}
	if err != nil {
		panic(err)
	}

	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		for {
			err := stream.Send(&proto.StreamReqData{Data: "xxx"})
			if err != nil {
				return
			}
		}
		wg.Done()
	}()

	go func() {
		for {
			recv, err := stream.Recv()
			if err != nil {
				return
			}
			fmt.Println("收到的信息", recv)
		}
		wg.Done()
	}()

	wg.Wait()

}
